﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WCSY.BLL;
using WCSY.MODEL;
using System.Data;

public partial class CostsManagement_costsApplyOrderList : System.Web.UI.Page
{
    Fg_deptInfoManager deptM = new Fg_deptInfoManager();
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack){
            //绑定申请部门
            DataTable deptList = deptM.GetAllList().Tables[0];
            this.ddlApplyDept.DataSource = deptList;
            this.ddlApplyDept.DataTextField = "deptname";
            this.ddlApplyDept.DataValueField = "deptno";
            this.ddlApplyDept.DataBind();
            gvBind();
            
        }
    }

    public void gvBind() {
        wcsy_costsOrderMstManager mstm = new wcsy_costsOrderMstManager();
       
        this.GridView1.DataSource = mstm.GetAllListByPara("","-1","","","","");
        this.GridView1.DataBind();
        
    }
    /// <summary>
    /// 查询
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSec_Click(object sender, EventArgs e)
    {
        wcsy_costsOrderMstManager mstm = new wcsy_costsOrderMstManager();
        string sysno = txtSysno.Text;
        string dept = ddlApplyDept.SelectedValue;
        string applypsn = txtApplyPsn.Text;
        string fillpsn = txtFillPsn.Text;
        string filldateB = txtFilldateB.Text;
        string filldateE = txtFilldateE.Text;
        this.GridView1.DataSource = mstm.GetAllListByPara(sysno, dept, applypsn, fillpsn, filldateB, filldateE);
        this.GridView1.DataBind();
    }
    /// <summary>
    /// 删除数据
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnDel_Click(object sender, EventArgs e)
    {
        //遍历每一行
        List<string> sqlList = new List<string>();
        wcsy_costsOrderMstManager mstm = new wcsy_costsOrderMstManager();
        wcsy_costsOrderDetManager detm = new wcsy_costsOrderDetManager();
        foreach (GridViewRow row in this.GridView1.Rows)
        {   //如果是数据行
            if (row.RowType == DataControlRowType.DataRow)
            {
                //判断复选框是否选中
                CheckBox cb = row.FindControl("orderCheckBox") as CheckBox;
                //判断是否选中没有
                if (cb.Checked)
                {
                    string id = this.GridView1.DataKeys[row.RowIndex]["sysno"].ToString();
                    
                    wcsy_costsOrderMst mst = mstm.GetMODEL(id);
                    if (mst.authorPsn!=null && !mst.authorPsn.Equals(""))
                    {
                        this.RegisterStartupScript("alert", "<script>alert('单据提交或审批，不允许删除！')</script>");
                        return;
                    }
                    sqlList.Add(mstm.Delete(id));
                    sqlList.Add(detm.Delete(id));
                    
                    //Response.Write("<script>alert('删除成功！');</script>");
                }
            }
        }
        try
        {
            string suc = tool.executeSqlTran(sqlList);
            if (!suc.Equals("suc"))
            {
                throw new Exception(suc);

            }
        }
        catch (Exception ex)
        {
            string error = ex.Message;
            error = error.Replace("\r\n", "");
            error = error.Replace("\n", "");
            error = error.Replace("\r", "");
            error = error.Replace("'", "");
            this.RegisterStartupScript("alert", "<script>alert('删除失败，请重新选择！" + error + "')</script>");
            return;

        }
        this.RegisterStartupScript("alert", "<script>alert('删除成功！')</script>");
        gvBind();
    }
    //送审单据，根据单据已定义审批流，增加单据审批步骤
    protected void btnToApprov_Click(object sender, EventArgs e)
    {
        //遍历每一行
        List<string> sqlList = new List<string>();
        fg_approveObjMstAppManager objmstm = new fg_approveObjMstAppManager();//审批步骤主表
        fg_approveObjDetAppManager objdetm = new fg_approveObjDetAppManager();//审批步骤明细表
        fg_approveFlowMstAppManager mstm = new fg_approveFlowMstAppManager();//审批流主表
        fg_approveFlowDetAppManager detm = new fg_approveFlowDetAppManager();//审批流明细表
        wcsy_costsOrderMstManager costmstm = new wcsy_costsOrderMstManager();//单据主表
        fg_operatesAppManager operam = new fg_operatesAppManager();//单据审批控制表，是否启用审批流
        Mg_roleManager rolem = new Mg_roleManager();
        foreach (GridViewRow row in this.GridView1.Rows)
        {   //如果是数据行
            if (row.RowType == DataControlRowType.DataRow)
            {
                //判断复选框是否选中
                CheckBox cb = row.FindControl("orderCheckBox") as CheckBox;
                try{
                //判断是否选中没有
                    if (cb.Checked)
                    {
 
                        string sysno = this.GridView1.DataKeys[row.RowIndex]["sysno"].ToString();

                        wcsy_costsOrderMst costmst = costmstm.GetMODEL(sysno);//单据主表信息

                        fg_approveFlowMstApp mst = mstm.GetModelByOpno("C0001");//费用单审批流控制号为C0001

                       //判断送审单据类型，是否启用审批流
                        DataTable operappdt = operam.GetList(" opNo = 'C0001' and isApp =1 ").Tables[0];
                        if (operappdt.Rows.Count > 0)
                        {//启用审批流
                            //1、判断是否启用默认审批
                            int isDefaultApp = Convert.ToInt32(operappdt.Rows[0]["isDefaultApp"]!=null?operappdt.Rows[0]["isDefaultApp"]:0);
                            if (isDefaultApp == 1)
                            {
                                //首先确认该选中单据是否具备送审条件（条件为：没有送审过，或审批过程中出现驳回情况，可重新送审）
                                //下面开始判断
                                DataTable objdetDt = objdetm.getApprovobjDet(" and fg_approveobjmstapp.billno='" + sysno + "' ");
                                DataRow[] drs = objdetDt.Select("checkflg = 2");
                                if (objdetDt.Rows.Count <= 0)
                                {//没有送审
                                    fg_approveObjMstApp objmst = new fg_approveObjMstApp();//审批步骤主表
                                    string objId = tool.GetMaxSysno("id", "fg_approveObjMstApp");
                                    objmst.id = objId;
                                    objmst.opNo = "C0001";
                                    objmst.billNo = sysno;
                                    objmst.sendPsn = costmst.applyPsn;//申请人为单据主表中申请人
                                    objmst.sendDate = DateTime.Now;
                                    sqlList.Add(objmstm.Add(objmst));
                                    //添加明细
                                    string roleId = tool.getRoleIdByUserId(costmst.applyPsn);
                                    mg_role role = rolem.GetModel(Convert.ToInt32(roleId));

                                    for (int i = 1; ; )
                                    {
                                        if (role.suPost != null && !role.suPost.Equals("-1") && !role.suPost.Equals(""))
                                        {
                                            fg_approveObjDetApp objdet = new fg_approveObjDetApp();//审批步骤明细表
                                            objdet.id = objId;
                                            objdet.lineid = i;
                                            objdet.flowStepNo = i;
                                            objdet.approvPsn = role.suPost.ToString();//是否应该添加岗位名称字段，这里只添加岗位代码字段。
                                            sqlList.Add(objdetm.Add(objdet));
                                            role = rolem.GetModel(role.suPost);
                                            i++;
                                        }
                                        else
                                        {
                                            break;
                                        }

                                    }
                                    //更改单据提交人


                                    costmst.authorPsn = Session["userId"].ToString();
                                    costmst.authorDate = DateTime.Now;

                                    sqlList.Add(costmstm.Update(costmst));
                                }
                                else if (drs.Length != 0)
                                {//驳回操作,重新送审
                                    sqlList.Add(objmstm.delApprovObjMstByBillno(sysno));//删除审批流主表
                                    sqlList.Add(objdetm.delApprovobjdetByBillno(sysno));//删除审批流明细表

                                    fg_approveObjMstApp objmst = new fg_approveObjMstApp();//审批步骤主表
                                    string objId = tool.GetMaxSysno("id", "fg_approveObjMstApp");
                                    objmst.id = objId;
                                    objmst.opNo = "C0001";
                                    objmst.billNo = sysno;
                                    objmst.sendPsn = costmst.applyPsn;//申请人为单据主表中申请人
                                    objmst.sendDate = DateTime.Now;
                                    sqlList.Add(objmstm.Add(objmst));
                                    //添加明细
                                    string roleId = tool.getRoleIdByUserId(costmst.applyPsn);
                                    mg_role role = rolem.GetModel(Convert.ToInt32(roleId));

                                    for (int i = 1; ; )
                                    {
                                        if (role.suPost != null && !role.suPost.Equals("-1") && !role.suPost.Equals(""))
                                        {
                                            fg_approveObjDetApp objdet = new fg_approveObjDetApp();//审批步骤明细表
                                            objdet.id = objId;
                                            objdet.lineid = i;
                                            objdet.flowStepNo = i;
                                            objdet.approvPsn = role.suPost.ToString();//是否应该添加岗位名称字段，这里只添加岗位代码字段。
                                            sqlList.Add(objdetm.Add(objdet));
                                            role = rolem.GetModel(role.suPost);
                                            i++;
                                        }
                                        else
                                        {
                                            break;
                                        }
                                    }

                                    //更改单据提交人


                                    costmst.authorPsn = Session["userId"].ToString();
                                    costmst.authorDate = DateTime.Now;

                                    sqlList.Add(costmstm.Update(costmst));
                                }
                                else
                                {
                                    tool.Alert("单据已提交或正在处理中，不允许送审！", this);
                                    return;
                                }
                                

                            }
                            else
                            {






                                //2、启用审批流程定义
                                DataTable detDt = detm.GetList("sysno = '" + mst.sysno + "' order by ordno").Tables[0];//费用单审批流明细定义表（审批顺序）
                                //首先确认该选中单据是否具备送审条件（条件为：没有送审过，或审批过程中出现驳回情况，可重新送审）
                                //下面开始判断
                                DataTable objdetDt = objdetm.getApprovobjDet(" and fg_approveobjmstapp.billno='" + sysno + "' ");
                                DataRow[] drs = objdetDt.Select("checkflg = 2");

                                if (objdetDt.Rows.Count <= 0)
                                {//没有送审
                                    fg_approveObjMstApp objmst = new fg_approveObjMstApp();//审批步骤主表
                                    string objId = tool.GetMaxSysno("id", "fg_approveObjMstApp");
                                    objmst.id = objId;
                                    objmst.opNo = "C0001";
                                    objmst.billNo = sysno;
                                    objmst.sendPsn = costmst.applyPsn;//申请人为单据主表中申请人
                                    objmst.sendDate = DateTime.Now;
                                    sqlList.Add(objmstm.Add(objmst));

                                    for (int i = 0; i < detDt.Rows.Count; i++)
                                    {
                                        fg_approveObjDetApp objdet = new fg_approveObjDetApp();//审批步骤明细表
                                        objdet.id = objId;
                                        objdet.lineid = Convert.ToInt32(detDt.Rows[i]["lineid"]);
                                        objdet.flowStepNo = Convert.ToInt32(detDt.Rows[i]["ordno"]);
                                        objdet.approvPsn = detDt.Rows[i]["approvPost"].ToString();//是否应该添加岗位名称字段，这里只添加岗位代码字段。
                                        sqlList.Add(objdetm.Add(objdet));
                                    }

                                    //更改单据提交人


                                    costmst.authorPsn = Session["userId"].ToString();
                                    costmst.authorDate = DateTime.Now;

                                    sqlList.Add(costmstm.Update(costmst));
                                }
                                else if (drs.Length != 0)
                                {//驳回操作,重新送审
                                    sqlList.Add(objmstm.delApprovObjMstByBillno(sysno));//删除审批流主表
                                    sqlList.Add(objdetm.delApprovobjdetByBillno(sysno));//删除审批流明细表

                                    fg_approveObjMstApp objmst = new fg_approveObjMstApp();//审批步骤主表
                                    string objId = tool.GetMaxSysno("id", "fg_approveObjMstApp");
                                    objmst.id = objId;
                                    objmst.opNo = "C0001";
                                    objmst.billNo = sysno;
                                    objmst.sendPsn = costmst.applyPsn;//申请人为单据主表中申请人
                                    objmst.sendDate = DateTime.Now;
                                    sqlList.Add(objmstm.Add(objmst));

                                    for (int i = 0; i < detDt.Rows.Count; i++)
                                    {
                                        fg_approveObjDetApp objdet = new fg_approveObjDetApp();//审批步骤明细表
                                        objdet.id = objId;
                                        objdet.lineid = Convert.ToInt32(detDt.Rows[i]["lineid"]);
                                        objdet.flowStepNo = Convert.ToInt32(detDt.Rows[i]["ordno"]);
                                        objdet.approvPsn = detDt.Rows[i]["approvPost"].ToString();//是否应该添加岗位名称字段，这里只添加岗位代码字段。
                                        sqlList.Add(objdetm.Add(objdet));
                                    }

                                    //更改单据提交人


                                    costmst.authorPsn = Session["userId"].ToString();
                                    costmst.authorDate = DateTime.Now;

                                    sqlList.Add(costmstm.Update(costmst));

                                }
                                else
                                {
                                    tool.Alert("单据已提交或正在处理中，不允许送审！", this);
                                    return;
                                }
                            }
                        }
                        else { //审批流未启用
                            tool.Alert("该单据类型未启用审批流，无法执行送审操作，请先启用审批流！",this);
                            return;
                        }
                        
                        

                        //if (mst.authorPsn != null && !mst.authorPsn.Equals(""))
                        //{
                        //    this.RegisterStartupScript("alert", "<script>alert('单据提交或审批，不允许删除！')</script>");
                        //    return;
                        //}
                        //sqlList.Add(mstm.Delete(id));
                        //sqlList.Add(detm.Delete(id));

                        //Response.Write("<script>alert('删除成功！');</script>");
                   
                }
                     }catch(Exception ex){
                         tool.Alert("送审失败！"+ex.Message, this);
                         return;
                    }
            }
        }
        try
        {
            string suc = tool.executeSqlTran(sqlList);
            if (!suc.Equals("suc"))
            {
                throw new Exception(suc);

            }
        }
        catch (Exception ex)
        {
            string error = ex.Message;
            error = error.Replace("\r\n", "");
            error = error.Replace("\n", "");
            error = error.Replace("\r", "");
            error = error.Replace("'", "");
            this.RegisterStartupScript("alert", "<script>alert('送审失败，请重新选择！" + error + "')</script>");
            return;

        }
        this.RegisterStartupScript("alert", "<script>alert('送审成功！')</script>");
    }



}
